<template>
  <teleport :to="to"
    ><div class="recordUserInfo-mark" v-if="showDialog">
      <transition name="fade">
        <div
          class="recordUserInfo-setup"
          :style="({ '--dialogWid': dialogWid } as any)"
          v-show="showDialogContent"
        >
          <div class="recordUserInfo-setup__title">
            <span>{{
              type === 0
                ? showRemark && showGroup
                  ? "设置备注和分组"
                  : showRemark && !showGroup
                  ? "设置备注"
                  : !showRemark && showGroup
                  ? "设置分组"
                  : ""
                : "设置朋友圈权限"
            }}</span>
            <SvgIcon icon-class="close" popper-class="title-close" @click="closeDialog" />
          </div>
          <div class="recordUserInfo-setup__main">
            <template v-if="type === 0">
              <el-form v-if="showRemark || showGroup" label-position="top" size="small">
                <el-form-item
                  v-if="showRemark"
                  class="form-item"
                  :label="`${showRemark && !showGroup ? ' ' : '备注名'}`"
                >
                  <el-input
                    ref="remarkRef"
                    v-model.trim="theInfoRemGroup.remark"
                    :disabled="isLoading"
                    maxlength="8"
                    @blur="blur(theInfoRemGroup.remark)"
                    @keypress.enter.prevent="groupFocus"
                  />
                </el-form-item>
                <el-form-item
                  v-if="showGroup"
                  class="form-item"
                  :label="`${showGroup && !showRemark ? ' ' : '分组'}`"
                >
                  <el-input
                    v-model.trim="theInfoRemGroup.group"
                    ref="groupRef"
                    :disabled="isLoading"
                    maxlength="16"
                    placeholder="设置分组"
                    @keypress.enter.prevent="startSubmit(0)"
                  />
                </el-form-item>
              </el-form>
              <template v-if="showGroup">
                <group-tags :disabled="isLoading" @change="groupChange"></group-tags>
              </template>
            </template>
            <template v-else>
              <moments-permission
                :disabled="isLoading"
                v-model="theInfoPermission"
              ></moments-permission>
            </template>
          </div>
          <div class="recordUserInfo-setup__footer">
            <el-button
              class="footer-cancel"
              :disabled="isLoading"
              style="height: 29px"
              @click="emits('update:modelValue', false)"
              >取消</el-button
            >
            <el-button
              class="footer-confirm"
              type="primary"
              style="height: 29px"
              :disabled="isLoading"
              :loading="isLoading"
              @click="startSubmit(type)"
              ><template #loading><Loading /></template>确认</el-button
            >
          </div>
        </div>
      </transition>
    </div></teleport
  >
</template>

<script lang="ts" setup>
import { ref, watch, watchEffect, nextTick } from "vue";
import { useFriendPinia } from "@/pinia/friend";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { deepClone } from "@/plugins/deepClone";
import { useRouter, useRoute } from "vue-router";
import groupTags from "@/components/groupTags.vue";
import momentsPermission from "@/components/momentsPermission.vue";

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    width?: number | string;
    infoRemGroup: {
      remark: string;
      group: string;
    };
    to?: string;
    infoPermission: Permission;
    // 对方的账号
    otherId: string;
    type?: 0 | 1;
    // 是否显示修改备注选项
    showRemark?: boolean;
    // 是否显示修改分组选项
    showGroup?: boolean;
  }>(),
  {
    to: "",
    type: 0,
    width: "45%",
    showGroup: true,
    showRemark: true,
  }
);
const emits = defineEmits<{
  (e: "update:modelValue", show: boolean): void;
  (e: "update:infoRemGroup", value: { remark: string; group: string }): void;
  (e: "update:infoPermission", value: Permission): void;
  (
    e: "success",
    payload: { userId: string; type: 0 | 1; remark?: string; disabledSelfLook?: boolean }
  ): void;
}>();

const router = useRouter();
const route = useRoute();

const friendStore = useFriendPinia();
const { isRequFriendsManage } = storeToRefs(friendStore);

/**
 * 对话框的宽度
 */
const dialogWid = ref<string>("");

watchEffect(() => {
  if (props.width) {
    if (!isNaN(+props.width)) dialogWid.value = `${props.width}px`;
    else if (
      typeof props.width === "string" &&
      (/^\d+%$/.test(props.width) || /^\d+px$/.test(props.width))
    )
      dialogWid.value = props.width;
  } else dialogWid.value = "40%";
});

/**
 * 修改后的备注和分组
 */
const theInfoRemGroup = ref<{ remark: string; group: string }>({
  remark: "",
  group: "",
});
// 当分组发生改变时
const groupChange = (group: string) => (theInfoRemGroup.value.group = group);

/**
 * 修改后的朋友圈权限
 */
const theInfoPermission = ref<Permission>({
  disabledOtherLook: false,
  disabledSelfLook: false,
});

/**
 * 给备注输入框一个ref属性，便于通过$refs访问
 */
const remarkRef = ref<any>();
/**
 * 给分组输入框一个ref属性，便于通过$refs访问
 */
const groupRef = ref<any>();
/**
 * 是否显示确认操作的对话框
 */
const showDialog = ref<boolean>(false);
/**
 * 是否显示确认操作的对话框的内容
 */
const showDialogContent = ref<boolean>(false);

// 分组输入框是否需要聚焦
const groupFocus = () => {
  props.showGroup ? groupRef.value.focus() : startSubmit(0);
};

watch(
  () => props.modelValue,
  (show: boolean) => {
    if (show) {
      if (props.type === 0) {
        theInfoRemGroup.value = deepClone(props.infoRemGroup);
        setTimeout(() => {
          props.showRemark
            ? remarkRef.value.focus()
            : props.showGroup
            ? groupRef.value.focus()
            : "";
        }, 200);
      } else theInfoPermission.value = deepClone(props.infoPermission);
      showDialog.value = true;
      nextTick(() => (showDialogContent.value = true));
    } else {
      showDialogContent.value = false;
      setTimeout(() => (showDialog.value = false), 200);
    }
  }
);

/**
 * 输入框失焦时触发的函数
 */
const blur = (value: string) =>
  value || (theInfoRemGroup.value.remark = props.infoRemGroup.remark);

// 是否正在发送请求进行修改
const isLoading = ref<boolean>(false);

// 开始提交修改
const startSubmit = (type: number) => {
  if (type === 0) {
    if (
      !(
        props.infoRemGroup.remark === theInfoRemGroup.value.remark &&
        props.infoRemGroup.group === theInfoRemGroup.value.group
      )
    ) {
      if (theInfoRemGroup.value.group === "无分组") {
        ElMessage({
          type: "warning",
          message: "该分组默认已经存在，请另设置一个",
          duration: 1500,
        });
        return;
      }
      isLoading.value = true;
      friendStore
        .updateRemGroup(
          {
            otherId: props.otherId,
            ...theInfoRemGroup.value,
          },
          props.infoRemGroup.group
        )
        .then((data: { code: number; initials: string }) => {
          isLoading.value = false;
          if (data.code === 1) {
            ElMessage({
              type: "success",
              message: "修改成功",
              duration: 1500,
            });
            emits("update:infoRemGroup", deepClone(theInfoRemGroup.value));
            emits("update:modelValue", false);
            emits("success", {
              userId: props.otherId,
              type: 0,
              remark: theInfoRemGroup.value.remark,
            });
            if (route.name === "friendInfo")
              router.replace({
                name: "friendInfo",
                query: { userId: props.otherId },
                params: { initials: data.initials },
              });
          } else if (data.code === -2)
            ElMessage({
              type: "error",
              message: "修改失败，对方和自己不是好友关系",
              duration: 1500,
            });
          else
            ElMessage({
              type: "error",
              message: "修改失败",
              duration: 1500,
            });
        })
        .catch(() => {
          isLoading.value = false;
          ElMessage({
            type: "error",
            message: "修改失败",
            duration: 1500,
          });
        });
    } else emits("update:modelValue", false);
  } else if (type === 1) {
    if (
      !(
        props.infoPermission.disabledOtherLook ===
          theInfoPermission.value.disabledOtherLook &&
        props.infoPermission.disabledSelfLook === theInfoPermission.value.disabledSelfLook
      )
    ) {
      const permission: {
        type: "disabledOtherLook" | "disabledSelfLook" | "other";
        count: 1 | -1;
        changeType: 0 | 1 | 2 | 3;
      } = {
        type: "disabledSelfLook",
        count: -1,
        changeType: 0,
      };
      // 如果请求了通讯管理数据的话
      if (isRequFriendsManage.value) {
        if (
          props.infoPermission.disabledOtherLook ===
            theInfoPermission.value.disabledOtherLook &&
          props.infoPermission.disabledSelfLook !==
            theInfoPermission.value.disabledSelfLook
        ) {
          // 代表只需要不看对方的总人数+1
          if (theInfoPermission.value.disabledSelfLook) permission.count = 1;
        } else if (
          props.infoPermission.disabledOtherLook !==
            theInfoPermission.value.disabledOtherLook &&
          props.infoPermission.disabledSelfLook ===
            theInfoPermission.value.disabledSelfLook
        ) {
          permission.type = "disabledOtherLook";
          // 代表只需要不让对方看的总人数+1
          if (theInfoPermission.value.disabledOtherLook) permission.count = 1;
        } else {
          permission.type = "other";
          if (
            theInfoPermission.value.disabledOtherLook &&
            theInfoPermission.value.disabledSelfLook
          )
            // 两方都需要+1
            permission.changeType = 1;
          else if (
            theInfoPermission.value.disabledOtherLook &&
            !theInfoPermission.value.disabledSelfLook
          )
            // 不让对方看的人数+1，自己不看的人数-1
            permission.changeType = 2;
          else if (
            !theInfoPermission.value.disabledOtherLook &&
            theInfoPermission.value.disabledSelfLook
          )
            // 不让对方看的人数-1，自己不看的人数+1
            permission.changeType = 3;
        }
      }
      isLoading.value = true;
      friendStore
        .updateMomPermission(
          {
            otherId: props.otherId,
            ...theInfoPermission.value,
          },
          props.infoRemGroup.group,
          isRequFriendsManage.value ? permission : undefined
        )
        .then((code: number) => {
          isLoading.value = false;
          if (code === 1) {
            ElMessage({
              type: "success",
              message: "修改成功",
              duration: 1500,
            });
            emits("update:infoPermission", deepClone(theInfoPermission.value));
            emits("update:modelValue", false);
            emits("success", {
              userId: props.otherId,
              type: 1,
              disabledSelfLook: theInfoPermission.value.disabledSelfLook,
            });
          } else if (code === -2)
            ElMessage({
              type: "error",
              message: "修改失败，对方和自己不是好友关系",
              duration: 1500,
            });
          else
            ElMessage({
              type: "error",
              message: "修改失败",
              duration: 1500,
            });
        })
        .catch(() => {
          isLoading.value = false;
          ElMessage({
            type: "error",
            message: "修改失败",
            duration: 1500,
          });
        });
    } else emits("update:modelValue", false);
  }
};

// 关闭窗口
const closeDialog = () => {
  if (!isLoading.value) emits("update:modelValue", false);
};
</script>

<style lang="scss" scoped>
.fade {
  @include fade(0.15s, ease);
}

.recordUserInfo {
  &-mark {
    position: absolute;
    inset: 0;
    z-index: 1002;
  }

  &-setup {
    position: absolute;
    background-color: #fff;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%, -50%, 0);
    width: var(--dialogWid);
    border-radius: 6px;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.12);
    padding: 3px 0 8px 0;

    &__title {
      position: relative;
      padding: 6px 10px 8px;

      span {
        font-size: 12px;
        color: $dimFontCor;
      }

      .title-close {
        position: absolute;
        right: 3%;
        top: 6px;
        color: #909399;
        cursor: pointer;
        transition: color 0.15s;

        &:hover {
          color: #79bbff;
        }
      }
    }

    &__main {
      padding: 0 25px;
      color: #606266;
      font-size: 13px;

      .form-item {
        margin-bottom: 12px;
      }
    }

    &__footer {
      padding: 15px 25px;

      .footer {
        &-cancel {
          width: 35%;
        }

        &-confirm {
          width: 35%;
          margin-left: 30%;
        }
      }
    }
  }
}
</style>
